<?php

namespace  app\command\controller;

use common\model\sell66\OutTrade;
use common\model\sell66\UserSteam;
use common\bot\SteamBotService;
use think\Exception;

/**
 * 发起取回报价
 * 
 * @author zhouqiang
 * @date 2018-06-05
 */
class SendOutTrade
{
	protected function getOutTradeByReading()
	{
		return OutTrade::getOutTradeByReading();
	}

	protected function getInfoByUserId($userId)
	{
		return UserSteam::getInfoByUserId($userId);
	}

	protected function rpcSendOutTrade($steamId, $tradeUrl, $trade)
	{
		return SteamBotService::getInstance()->rpcSendOutTrade($steamId, $tradeUrl, $trade);
	}

	protected function updateOutTradeByTradeoffOutId($outTradeId, $tradeoffoutId)
	{
		return OutTrade::updateOutTradeByTradeoffOutId($outTradeId, $tradeoffoutId);
	}

	public function sendTrade()
	{
		$trades = $this->getOutTradeByReading();
		if (!$trades) {
			echo 'query reading out trade failed'."\r\n";
			return false;
		}

		foreach ($trades as $trade) {
			$this->sendOutTrade($trade['out_trade_id'], $trade['user_id'], $trade);
		}

		return true;
	}

	protected function sendOutTrade($outTradeId, $userId, array $trade)
	{
		$user = $this->getInfoByUserId($userId);
		if (!$user) {
			echo 'query user info failed, user_id:'.$userId."\r\n";
			return false;
		}

		$details = $trade['out_trade_detail'];
		$trade = array(
			'bot_id' => $trade['bot_id'],
		);

		foreach ($details as $detail) {
			$trade['oids'][] = array(
				'app_id' => $detail['app_id'],
				'o_id' => $detail['o_id'],
			);
		}

		$res = $this->rpcSendOutTrade($user['steam_id'], $user['trade_off_url'], array($trade));
		if (!$res['code']) {
			echo 'send out trade failed, out_trade_id:'.$outTradeId."\r\n";
			return false;
		}

		$tradeoff = current($res['data']);

		$res1 = $this->updateOutTradeByTradeoffOutId($outTradeId, $tradeoff['outTradeId']);
		if (!$res1) {
			echo 'update new out trade id failed, out_trade_id:'.$outTradeId."\r\n";
			return false;
		}

		echo 'update new out trade id success, out_trade_id:'.$outTradeId."\r\n";
		return true;
	}


	public function handle()
	{
		$this->sendTrade();
		echo '数据查询完毕！'."\r\n";
		return true;
	}
}